package com.yaowk.sfp.utils.verification.sms.aliyun;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.libfintech.verification.service.BaseSmsService;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author 小凯
 **/
@Slf4j
public class AliYunSmsService extends BaseSmsService<AliYunSmsConfig> {

    private final AliYunSmsConfig CONFIG;
    private IAcsClient acsClient;

    private final Map<String, String> templateCodes = new ConcurrentHashMap<>();
    private final Map<String, String> signNames = new ConcurrentHashMap<>();

    public AliYunSmsService(AliYunSmsConfig config) {
        super(config);
        CONFIG = config;
        IClientProfile clientProfile = DefaultProfile.getProfile(CONFIG.getRegion(), CONFIG.getAccessKeyId(), CONFIG.getAccessKeySecret());
        try {
            DefaultProfile.addEndpoint(CONFIG.getRegion(), CONFIG.getRegion(), CONFIG.getProduct(), CONFIG.getDomain());
        } catch (ClientException e) {
            e.printStackTrace();
            throw new RuntimeException("阿里大鱼短信工具初始化失败");
        }
        acsClient = new DefaultAcsClient(clientProfile);
    }

    @Override
    public void send(String s, String s1) {
        if (CONFIG.getSend()) {
            String key = s + s1;
            String templateCode = templateCodes.getOrDefault(key, CONFIG.getTemplateCode());
            String signName = signNames.getOrDefault(key, CONFIG.getSignName());
            SendSmsRequest request = new SendSmsRequest();
            request.setMethod(MethodType.POST);
            request.setPhoneNumbers(s);
            request.setSignName(signName);
            request.setTemplateCode(templateCode);
            request.setTemplateParam(s1);

            try {
                SendSmsResponse response = acsClient.getAcsResponse(request);
                if (!"OK".equals(response.getCode())) {
                    log.info(response.getMessage());
                    throw new RuntimeException(response.getMessage());
                }
            } catch (ClientException e) {
                e.printStackTrace();
                throw new RuntimeException("阿里大鱼短信发送失败");
            }
        }
    }

    public void put(String s, String s1, String templateCode, String signName) {
        String key = s + s1;
        templateCodes.put(key, templateCode);
        signNames.put(key, signName);
    }

    public void remove(String s, String s2) {
        String key = s + s2;
        templateCodes.remove(key);
        signNames.remove(key);
    }
}
